package com.picrepo.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import com.picrepo.app.AppData;

import android.os.AsyncTask;
import android.util.Log;

public class LoginTask extends AsyncTask<String, String, String>
{
	private static final String TAG = LoginTask.class.getSimpleName();//"Vtag";
	private OnLoginListerner mOnLoginListerner;
	
	/**
	 * The login listener interface.
	 */
	public interface OnLoginListerner {
		/**
		 * Invoked when login successfully.
		 */
		void onSuccess(String result);
		/**
		 * Invoked when fail to login.
		 */
		void onFailure();
	}
	
	/**
	 * Set login listener.
	 * 
	 * @param l the login listener
	 */
	public void setOnLoginListerner(OnLoginListerner l) {
		this.mOnLoginListerner = l;
	}
	
	@Override
	protected String doInBackground(String... params) {
		HttpClient httpClient = new DefaultHttpClient();
		final HttpPost httpPost = new HttpPost(AppData.ACCOUNT_POST_URL);
		final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
		
		/* set parameter for the entity builder */
		entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		entityBuilder.setCharset(Charset.forName(HTTP.UTF_8));
		
		/* get the paramter and change to json */
		Map<String, String> user = new HashMap<String, String>();
		user.put("username", params[0]);
		user.put("password", params[1]);
		String json = new JSONObject(user).toString();
		StringBody strBody = new StringBody(json, ContentType.APPLICATION_JSON);
		entityBuilder.addPart("userinfo", strBody);
		
		/* build the entity builder */
		HttpEntity httpEntity = entityBuilder.build();
		httpPost.setEntity(httpEntity);
		try {
			HttpResponse response = httpClient.execute(httpPost);
			final int code = response.getStatusLine().getStatusCode();
			if (code == HttpStatus.SC_OK) {
				Log.d(TAG, "get response");
				
				BufferedReader br = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				StringBuilder builder = new StringBuilder();
				
	            String line;
	            while ((line = br.readLine()) != null) {
	            	builder.append(line+"\n");
	            }
	            br.close();
	          
	            return builder.toString();
			}
		} catch (ClientProtocolException e) {
			Log.d(TAG, e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			Log.d(TAG, e.getMessage());
			e.printStackTrace();
		} finally {
			if (httpClient != null) {
				httpClient.getConnectionManager().shutdown();
				httpClient = null;
			}
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);

		if (mOnLoginListerner != null){
			if (result == null) {
				mOnLoginListerner.onFailure();
			} else {
				mOnLoginListerner.onSuccess(result);
			}
		}
	}
}
